package com.beidu.lottery.call.mq.rocket.producer;

import cn.hutool.core.util.StrUtil;
import com.beidu.lottery.call.constant.RocketMQConstant;
import com.beidu.lottery.call.mq.event.ActivityDelayCloseEvent;

import com.beidu.lottery.call.mq.event.BaseSendExtendDTO;
import com.beidu.lottery.call.mq.event.MessageWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 活动延时关闭生产者
 * <p>
 * 作者：北渡
 */
@Slf4j
@Component
public class ActivityDelayCloseProducer extends AbstractCommonSendProduceTemplate<ActivityDelayCloseEvent> {

    private final ConfigurableEnvironment environment;

    public ActivityDelayCloseProducer(@Autowired RocketMQTemplate rocketMQTemplate, @Autowired ConfigurableEnvironment environment) {
        super(rocketMQTemplate);
        this.environment = environment;
    }

    @Override
    protected BaseSendExtendDTO buildBaseSendExtendParam(ActivityDelayCloseEvent messageSendEvent) {
        return BaseSendExtendDTO.builder()
                .eventName("延迟关闭修改活动状态")
                .keys(String.valueOf(messageSendEvent.getActivityId()))
                .topic(environment.resolvePlaceholders(RocketMQConstant.ACTIVITY_DELAY_CLOSE_TOPIC_KEY))
                .sentTimeout(2000L)
                .delayLevel(14)//RocketMQ 延迟消息级别 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
                .build();
    }

    @Override
    protected Message<?> buildMessage(ActivityDelayCloseEvent messageSendEvent, BaseSendExtendDTO requestParam) {
        String keys = StrUtil.isEmpty(requestParam.getKeys()) ? UUID.randomUUID().toString() : requestParam.getKeys();
        return MessageBuilder
                .withPayload(new MessageWrapper(requestParam.getKeys(), messageSendEvent))
                .setHeader(MessageConst.PROPERTY_KEYS, keys)
                .setHeader(MessageConst.PROPERTY_TAGS, requestParam.getTag())
                .build();
    }
}
